from django.contrib import admin
from django.utils import timezone
from django.utils.timezone import localtime
from .models import EvalList, EvalQuestion
import pandas as pd
from django.http import HttpRequest, HttpResponse


def export_to_csv(modeladmin, request, queryset):
    """
    导出所选数据为csv文件
    """
    # 获取字段名
    columns = [field.name for field in EvalList._meta.fields]

    # 创建DataFrame
    df = pd.DataFrame(list(queryset.values(*columns)), columns=columns)
    df["student_name"] = ""
    df["student_id"] = ""

    # 创建http响应
    response = HttpResponse(content_type="text/csv")
    response["Content-Disposition"] = "attachment; filename=evaluation_list.csv"

    # 写入csv文件
    df.to_csv(path_or_buf=response, index=False)

    return response


export_to_csv.short_description = "导出所选的数据为csv文件"


class EvalDateFilter(admin.SimpleListFilter):
    """
    自定义筛选器，筛选评测日期
    """

    title = "评测日期"
    parameter_name = "eval_date"

    def lookups(self, request, model_admin):
        return (
            ("today", "今天"),
            ("last_7_days", "最近7天"),
            ("this_month", "本月"),
            ("last_3_months", "近三个月"),
        )

    # 使用 localtime 函数将当前时间转换为本地时间，然后进行筛选。这样可以确保筛选条件不受时区影响
    def queryset(self, request, queryset):
        now = timezone.now()
        if self.value() == "today":
            start_of_today = localtime(now).replace(
                hour=0, minute=0, second=0, microsecond=0
            )
            end_of_today = start_of_today + timezone.timedelta(days=1)
            return queryset.filter(eval_date__range=(start_of_today, end_of_today))
        if self.value() == "last_7_days":
            start_of_last_7_days = localtime(now) - timezone.timedelta(days=7)
            return queryset.filter(eval_date__gte=start_of_last_7_days)
        if self.value() == "this_month":
            start_of_this_month = localtime(now).replace(
                day=1, hour=0, minute=0, second=0, microsecond=0
            )
            return queryset.filter(eval_date__gte=start_of_this_month)
        if self.value() == "last_3_months":
            start_of_last_3_months = localtime(now) - timezone.timedelta(days=90)
            return queryset.filter(eval_date__gte=start_of_last_3_months)


@admin.register(EvalList)
class EvalListAdmin(admin.ModelAdmin):
    list_display = (
        "eval_id",
        "class_name",
        "course_name",
        "teacher_name",
        "score1",
        "score2",
        "score3",
        "score4",
        "score5",
        "score6",
        "score7",
        "score8",
        "score",
        "eval_date",
    )
    # 增加执行动作，导出csv文件
    actions = [export_to_csv]
    search_fields = (
        "class_name",
        "teacher_name",
        "course_name",
    )
    list_filter = (
        # "eval_date", # 日期筛选
        EvalDateFilter,  # 自定义筛选器
    )

    # 禁止修改和删除
    def has_change_permission(self, request, obj=None):
        return False

    def has_add_permission(self, request):
        return False

    def has_delete_permission(self, request, obj=None):
        return False


@admin.register(EvalQuestion)
class EvalQuestionAdmin(admin.ModelAdmin):
    list_display = (
        "question_id",
        "item",
        "question",
        "weight",
    )
    search_fields = (
        "item",
        "question",
    )
